package com.ctshk.rpc.cms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SupplierStatus;
import com.ctshk.common.utils.HttpUtils;
import com.ctshk.rpc.cms.dto.BranchOfficeDTO;
import com.ctshk.rpc.cms.mapper.BranchOfficeMapper;
import com.ctshk.rpc.cms.req.BOQueryReq;
import com.ctshk.rpc.cms.req.DistanceQueryReq;
import com.ctshk.rpc.cms.service.IBaiDuApiService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class BaiDuApiServiceImpl implements IBaiDuApiService {

    private String url = "http://api.map.baidu.com/routematrix/v2/driving";
    private String ak = "cGksgHAP1phHdWnK0ZPIWFhlVK72lIGb";
    public static String BRANCH_OFFICE_KEY = "BRANCH_OFFICE_KEY";
    @Autowired
    private BranchOfficeMapper branchOfficeMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result getDistance(DistanceQueryReq dqr) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("output", "json");
        paramMap.put("ak", ak);
        paramMap.put("origins", dqr.getOrigins());
        paramMap.put("destinations", dqr.getDestinations());
        String result = HttpUtils.httpget(url, paramMap);
        return Result.success(result);
    }

    @Override
    public Result<List<BranchOfficeDTO>> query(BOQueryReq req) {
        List<BranchOfficeDTO> bos = null;
        ValueOperations ops = redisTemplate.opsForValue();
        //先取缓存不存在就重新查
        String opsBpl = (String) ops.get(BRANCH_OFFICE_KEY);
        if (StringUtils.isNotBlank(opsBpl)) {
            JSONArray jsonArray = JSON.parseArray(opsBpl);
            bos = jsonArray.toJavaList(BranchOfficeDTO.class);
        } else {
            bos = branchOfficeMapper.getBranchOffices(req.getLat(), req.getLon(), IsDeletedCode.NO.getCode(), SupplierStatus.ENABLE.getCode());
            if(bos != null){
                ops.set(BRANCH_OFFICE_KEY, JSON.toJSONString(bos));
            }
        }
        return Result.success(bos);
    }
}
